<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :sm="24" :lg="24">
        <hr />
      </el-col>
    </el-row>
    <el-row :gutter="20">
     
    </el-row>
    <el-divider />
    <el-row :gutter="20">
    </el-row>

      <!-- 遮罩层和进度条 -->
      <div v-if="uploadProgress > 0" class="upload-overlay" @click.prevent>
      <el-progress :percentage="uploadProgress"></el-progress>
    </div>

    <el-dialog :title="title" :visible.sync="openWarning" width="600px" append-to-body>
      <!-- <div slot="footer" > -->
       <div class="dialog-body">
        检测到当前服务器有挂载USB,可能存在文件需要导入,请问是否继续进行文件导入操作?
        <!-- 检测到有鉴权成功的移动硬盘插入请点击确认按钮进行内容卡拷贝- -->
       </div>
       <div slot="footer" >
          <el-button type="primary" @click="yes">立刻导入</el-button>
          <el-button @click="no">暂时不导入</el-button>
        </div>
      <!-- </div> -->
    </el-dialog>

     <el-dialog :title="title" :visible.sync="openDataScope" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="视频分类" prop="videoType">
          <el-select v-model="form.videoType" placeholder="请选择内容分类" @change="changeTvType">
            <el-option v-for="item in tvTypeOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status == 1" ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="剧情类型" prop="plotType" v-if="tvDataFlag">
          <el-select v-model="form.plotType" placeholder="请选择内容类型详情">
            <el-option v-for="item in tvDataOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status == 1"></el-option>
            </el-select>
        </el-form-item> -->
        <el-form-item label="文件目录">
          <el-tree
      style="max-width: 600px"
      :data="treeData"
      :props="treeProps"
      :load="loadNode"
      lazy
      show-checkbox
      ref="tree"
    ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitData">确 定</el-button>
        <el-button @click="cancelData">取 消</el-button>
      </div>
    </el-dialog>


     <!-- 上传完成提示框 -->
     <el-dialog :title="uploadSuccessTitle" :visible.sync="uploadSuccessVisible" width="500px" append-to-body>
      <div>文件上传完成,请到内容管理模块查看上传的文件记录</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeUploadSuccessDialog()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import { checkUsb,getFileData,getFileDataByPath,getContentType,getContentTypeData } from '@/api/index';
import { getToken } from "@/utils/auth";

export default {
  name: "Index",
  dicts: ['sys_video_type',"sys_plot_type"],
  data() {
    return {
      // 版本号
      version: "3.8.9",
      timer: null, // 定时器变量
      numberRow: 2,
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf',
      },
      uploadProgress: 0,//上传进度
      uploadTaskId: null, // 用于存储后端返回的上传任务ID
      timer: null, // 用于存储定时器ID
      selectedFiles: [], // 用于存储选中目录下的文件
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openWarning: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 内容分类选项
      tvTypeOptions: [],
      // 内容分类的类型详情选项
      tvDataOptions: [],
      tvDataFlag:false,
      // 表单参数
      form: {
        videoType:null,
        plotType:null,
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        // videoType: [
        //   { required: true, message: "视频分类不能为空", trigger: "blur" }
        // ],
        // plotType: [
        //   { required: true, message: "剧情类型不能为空", trigger: "blur" }
        // ],      
      },
      // 上传完成提示框相关属性
      uploadSuccessTitle: "上传完成",
      uploadSuccessVisible: false,
    };
  },
  mounted() {
    // 在组件挂载后启动定时器
    this.timer = setInterval(() => {
        this.fetchData(); // 调用获取数据的方法
    }, 10000); // 每5秒执行一次5000==>10秒

  },
  
  methods: {

    handleNodeClick(data, resolve ) {
      console.log("点击指定文件目录: "+data.path);
      // 点击节点时，获取当前节点的路径信息（这里假设data.path为节点路径）
      const path = data.path;
      getFileDataByPath(path).then(response => {
          console.log("获取指定文件: "+path+" 文件数据:"+JSON.stringify(response.data));
          this.selectedFiles = response.data;
        });
    },

    loadNode(node, resolve) {
      console.log("loadNode: "+node+"============"+node.level);
      //获取内容分类配置和剧情类型详情
      if (node.level === 0) {
        // 根节点请求后端获取数据
        getFileData().then(response => {
          resolve(response.data);
        });
      } else {
        console.log("模拟数据");
        const selectedNodeResultData = node.data;
        console.log("selectedNodeResultData: "+JSON.stringify(selectedNodeResultData));
        if (selectedNodeResultData &&!selectedNodeResultData.leaf) {
          const path = selectedNodeResultData.path;
          console.log("path: "+path);
          getFileDataByPath(path).then(response => {
            const children = response.data;
            resolve(children);
          });
        } else {
          resolve([]);
        }
      }
    },
    async fetchData() {
      try {
        console.log("发送定时任务检测系统是否有USB挂载");
        const response = await checkUsb(); // 调用API函数
        console.log('请求成功:', JSON.stringify(response));
        // 处理响应数据
        var data = response.data;
        console.log(JSON.stringify(data)+"======,弹框进行文件导入: "+this.openDataScope+" ,弹框提示: "+this.openWarning)
        if(data){
          //弹框展示
          if(!this.openWarning){
            this.openWarning = true;
            var row = this.numberRow;
            this.handleUpdate(row);
          }
        }else{
          //不存在或者已弹框
          this.no();
        }
      } catch (error) {
        console.error('发送定时任务,检测系统是否有挂载USB.请求失败:', error);
        // 处理错误
        this.no();
      }
    },
    beforeDestroy() {
      console.log("定时器被销毁");
    // 在组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  closeUploadSuccessDialog() {
      this.uploadSuccessVisible = false; // 隐藏上传完成提示框
  },
  no(){
    this.openWarning = false;
    this.openDataScope = false;
    this.beforeDestroy();
    console.log("销毁定时器");
  },
  yes(){
    this.openWarning = false;
    this.openDataScope = true;
    this.beforeDestroy();
  },
   // 表单重置
   reset() {
      this.form = {
        videoType: [],
        plotType: [],
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "导入USB文件";
    },
    submitData: function (){
      this.$refs["form"].validate(valid => {
        console.log("============提交校验:"+valid+"=======&&&&&&&&&&==="+JSON.stringify(this.form));
        if (valid) {
          const checkedNodes = this.$refs.tree.getCheckedNodes();
      console.log("提交信息 checkedNodes : "+JSON.stringify(checkedNodes));
      const filePaths = checkedNodes.map(node => node.path);
      console.log("提取需要上传的文件信息:"+JSON.stringify(filePaths)+"========"+filePaths.length);
      if(filePaths.length == 0){
        this.$modal.msgError("请选择上传的文件");
        return;
      }
      // this.$refs["form"].validate(valid => {
        const token = getToken();
        console.log("formData: "+JSON.stringify(filePaths)+"======="+this.form);
        var data = {
          filePaths:filePaths,
          // videoType:this.form.videoType,
          plotType:this.form.plotType,
        };
        console.log("提交数据: "+JSON.stringify(data));
        axios.post('/dev-api/api/startUpload', data , {
          headers: {
            'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
          },
        }).then(response => {
            var code = response.data.code;
            console.log("文件上传响应: "+JSON.stringify(response.data));
            if(code == 200){
              this.uploadTaskId = response.data.data;
              document.body.style.overflow = 'hidden'; // 禁用页面滚动
              this.timer = setInterval(() => {
                console.log("启动定时器");
                this.getUploadProgress();
              }, 1000);
            }else{
                this.$modal.msgError("上传失败");
                this.uploadProgress = 0;
            }
        }).catch(error => {
            console.error('上传失败', error);
            this.uploadProgress = 0;
        });
      // });


        }
      });

    },
    cancelData: function(){
      console.log("文件上传取消");
      this.openDataScope = false;
      this.reset();
    },
    getUploadProgress() {
      // console.log("getUploadProgress uploadTaskId: "+this.uploadTaskId);
      const token = getToken();
      axios.get(`/dev-api/api/uploadProgress/${this.uploadTaskId}`,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          this.uploadProgress = response.data.progress;
          console.log("进度条: "+this.uploadProgress+"==========="+response.data.total);
          if (response.data.progress === 100) {
            clearInterval(this.timer);
            this.openDataScope = false;
            // this.$modal.msgSuccess("文件上传完成,请到内容管理模块查看上传的文件记录");
            document.body.style.overflow = 'auto'; // 恢复页面滚动
            this.uploadProgress = 0; // 重置上传进度，隐藏遮罩层
            this.uploadSuccessVisible = true; // 显示上传完成提示框
          }
        })
        .catch(error => {
          console.error('获取上传进度失败', error);
        });
      }
   },
  }
</script>


<style scoped>
/* 遮罩层样式 */
.upload-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保遮罩层在最上层 */
}

/* 进度条样式 */
.upload-overlay .el-progress {
  width: 50%; /* 进度条宽度 */
}
</style>